import Web3 from 'web3'
import USDT from './bnbUsdt.json'
import DAPP from './dapp.json'
import COM from './commont.json'
import GK from './gk.json'
import JJC from './jjc.json'
import DB from './db.json'
import GZ from './gz.json'
import LP from './lp.json'
import JS from './js.json'
import { Toast } from 'vant';
// const { ethers } = require("ethers");
//正式
// const ADDRESS_COMMONT ="0xe6d883D4147C23348760d1D135A2E187825979e1"//公共合约
// const ADDRESS_GKHY ="0x0fa6c0Bd9704a7a45B16e0487549B10218A82bAa"//国库合约
// const ADDRESS_JJCHY ="0xCeA188c6bb0dB78Fd17904C03e28F43AE4e46d5a"//奖金池合约
// const ADDRESS_DAPP ="0xd97234BCa79c0EB5515cC4e5Af93f99fC2082099"//主合约
// const ADDRESS_USDT ="0x55d398326f99059fF775485246999027B3197955"//USDT合约
// const ADDRESS_FPC="0xB192D4A737430AA61CEA4Ce9bFb6432f7D42592F"//代币合约
// const ADDRESS_DB='0x270db1358993Ab42cf09c681308689Cb65A62619'//单币合约
// const ADDRESS_GZ='0xd49fC3E030F9dEA2437BA1069bF9A59026C00eDD'//国债合约
// const ADDRESS_LP='0x5434987AeFD45Fd719C77c1Cb7655F57a827D3c3'//Lp合约
// const ADDRESS_JS="0x2fBb00162dE57eb24408E653B766c5Fc5529cDa0"//结算合约
// const ADDRESS_LPFPC="0xa1e08E10Eb09857A8C6F2Ef6CCA297c1a081eD6B"//交易对合约

//测试
const ADDRESS_COMMONT ="0x52aDb647F8f05A28Be72FA7B342674075A6a7D88"//公共合约
const ADDRESS_GKHY ="0x23f07Fe5b5F8e71E0304b066235956aD8da909Cc"//国库合约
const ADDRESS_JJCHY ="0x21ADa66E18B74f62104c1f5c87608AF7243ac2A3"//奖金池合约
const ADDRESS_DAPP ="0xD62B72605b7638bf17A664A0C7a6375F333F7076"//主合约
const ADDRESS_USDT ="0x55d398326f99059fF775485246999027B3197955"//USDT合约
const ADDRESS_FPC="0x2344EBAba28c2ee08DD2740D71F5da00A1a44eeB"//代币合约
const ADDRESS_DB='0xB06983E05De666fC96C119b9aE5663292aD8C4F7'//单币合约
const ADDRESS_GZ='0xE43B1fAA1eE45cf3a42EF4bbEF463bb25e89056E'//国债合约
const ADDRESS_LP='0xfd347DcFD31aCC06d6930bA87B7999a3d0775687'//Lp合约
const ADDRESS_JS="0x387115B387a4454A0bA0F05531EA088136E5663A"//结算合约
const ADDRESS_LPFPC="0xCaCD5B2C714Ad262Eb0b705E66B5A99cc6EE12A2"//交易对合约

let ethereum = window.ethereum
// const provider = new ethers.providers.Web3Provider(window.ethereum);
// const signer = provider.getSigner();
    let i = setInterval(() => {
    if ((typeof window.ethereum) !== 'undefined') {
        ethereum = window.ethereum    
          
        handleWatch()  
        clearInterval(i)  
    }
    }, 1000);

export async function set(){
    ethereum = window.ethereum
}


export async function handleWatch () {
    if (!window.ethereum) {
        console.log('Metamask is not installed!')
        return false
      }
    window.ethereum.on('accountsChanged',  (accounts) => {
      if(accounts[0]){
        // let web3s = new Web3(ethereum);
        // let msg = web3s.utils.keccak256('授权签名');
        // let ht= await web3s.eth.sign(msg, accounts[0])
        // .then(res=>{return res});  
        // if(ht){
      sessionStorage.setItem('userWallet',accounts[0])  
    //   store.commit("userWallet", accounts[0]);  
    }else{
        sessionStorage.removeItem('userWallet')
      }     
    })
  }
export async function connectTron() {
    let web3s = new Web3(ethereum);
    // console.log(web3s.utils.toDecimal(ethereum.chainId),ethereum.chainId);
    if (web3s.utils.toDecimal(ethereum.chainId)!=56) {
        try {
            await window.ethereum.request({
                method: 'wallet_switchEthereumChain',
                params: [{
                    chainId: Web3.utils.numberToHex(56), // 目标链ID
                }]
            })
        } catch (e) {
            if (e.code == 4902) {
                try {
                    await window.ethereum.request({
                        method: 'wallet_addEthereumChain',
                        params: [{
                            chainId: Web3.utils.numberToHex(56), // 目标链ID
                            chainName: 'Arbitrum One',
                            nativeCurrency: {
                                name: 'ETH',
                                symbol: 'ETH',
                                decimals: 18
                            },
                            rpcUrls: ['https://bsc-dataseed.binance.org'], // 节点
                            blockExplorerUrls: ['https://bsc-dataseed.binance.org']
                        }]
                    })
                    return true
                } catch (ee) {
                    console.log('//---------', ee);

                }
            } else if (e.code === 4001) return false
        }    
    }
    const eth_requestAccounts = await ethereum.request({ method: "eth_requestAccounts" });
    // store.commit("userWallet", eth_requestAccounts[0]);
    return eth_requestAccounts
}

// 签名
export function Sign(address) {
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let msg = web3s.utils.utf8ToHex('Welcome to Future protocol');
        console.log(msg,address);
        let ht= await web3s.eth.personal.sign(msg, address)
        .then(res=>{return res}).catch(err=>{
          // Toast(err)
          console.log(err);
          return false});
       return ht?ht:false
  };
  return run();
  }

// 获取全网算力
export function getContTotalPower() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);      
        let unioContract1 = await new web3s.eth.Contract(DB, ADDRESS_DB);
        let unioContract2 = await new web3s.eth.Contract(GZ, ADDRESS_GZ);
        let unioContract3 = await new web3s.eth.Contract(LP, ADDRESS_LP);
        let unioContract4 = await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);
        let r1 = await unioContract1.methods.totalPower().call();
        let r2 = await unioContract2.methods.totalPower().call();
        let r3 = await unioContract3.methods.totalPower().call();
        let r4 = await unioContract4.methods.totalEquityPower().call();
        let r5=(BigInt(r1)+BigInt(r2)+BigInt(r3)+BigInt(r4)).toString()
      
        return r5
        
    };
    return run();
  }


// 冻结
export  function toSetBlack(address,user){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(COM, ADDRESS_COMMONT);
       let gas =await web3s.eth.getGasPrice()
        let result = await unioContract.methods.addToBlacklist(user).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}


// 解除冻结
export  function toSetRemveBlack(address,user){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(COM, ADDRESS_COMMONT);
       let gas =await web3s.eth.getGasPrice()
        let result = await unioContract.methods.removeFromBlacklist(user).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}
// 查询冻结状态
export function getUserBlack(address) {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(COM, ADDRESS_COMMONT);
          let result = await unioContract.methods.isBlacklisted(address).call();         
         return  result        
    };
    return run();
  }
  export function getFactor() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);      
        let unioContract = await new web3s.eth.Contract(COM, ADDRESS_COMMONT);
        let result = await unioContract.methods.factor().call();    
        return result   
    };
    return run();
  }

// 设置系数
export  function toSetFactor(address,num){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(COM, ADDRESS_COMMONT);
       let gas =await web3s.eth.getGasPrice()
        let result = await unioContract.methods.setFactor(num).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}


// 设置静态算力最小值 100 ether
export  function toSetMinStaticPower(address,num){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(COM, ADDRESS_COMMONT);
       let gas =await web3s.eth.getGasPrice()
        let result = await unioContract.methods.setMinStaticPower(num).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}

// 设置社区算力最小值 1000 ether
export  function toSetMinCommunityPower(address,num){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(COM, ADDRESS_COMMONT);
        console.log(unioContract,'---------');
       let gas =await web3s.eth.getGasPrice()
        let result = await unioContract.methods.setMinCommunityPower(num).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}

// 国库合约操作
// 国库后台提现
export  function toOwnerWithdraw(token,user,address,num){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let tokens=token==1?ADDRESS_USDT:token==2?ADDRESS_FPC:token==3?ADDRESS_LPFPC:""
        let unioContract = await new web3s.eth.Contract(GK, ADDRESS_GKHY);
       let gas =await web3s.eth.getGasPrice()
       let amount = web3s.utils.toWei(num + '','ether');
        let result = await unioContract.methods.ownerWithdraw(tokens,user,amount).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}
export function getGksinfo() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(GK, ADDRESS_GKHY);
          let r1 = await unioContract.methods.totalBuyUsdt().call();// 总购买USDT数量
          let r2 = await unioContract.methods.totalBuyGalaxy().call(); // 总购买Galaxy数量
          let r3 = await unioContract.methods.totalSellUsdt().call();   // 总出售USDT数量
          let r4 = await unioContract.methods.totalSellGalaxy().call();    // 总出售Galaxy数量
         return {r1,r2,r3,r4}
        
    };
    return run();
  }
// 国库买入 USDT的数量
export  function toOwnerBuy(address,num){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(GK, ADDRESS_GKHY);
        console.log(num, '买入数量');
        let gas =await web3s.eth.getGasPrice()
        console.log(gas, 'gas');
       let amount = web3s.utils.toWei(num + '','ether');
       console.log(amount, '买入数量');
        let result = await unioContract.methods.buy(amount).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}
// 国库卖出 代币的数量
export  function toOwnerSell(address,num){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(GK, ADDRESS_GKHY);
       let gas =await web3s.eth.getGasPrice()
       let amount = web3s.utils.toWei(num + '','ether');
        let result = await unioContract.methods.buy(amount).sell({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}

// 奖金池

// 查询每日释放比例
export function getDailyRatio() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(JJC, ADDRESS_JJCHY);
          let result = await unioContract.methods.dailyRatio().call();         
         return  result        
    };
    return run();
  }
// 查询动态比例
export function getDynamicRatio() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(JJC, ADDRESS_JJCHY);
          let result = await unioContract.methods.dynamicRatio().call();         
         return  result        
    };
    return run();
  }
// 查询静态比例
export function getStaticRatio() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(JJC, ADDRESS_JJCHY);
          let result = await unioContract.methods.staticRatio().call();         
         return  result        
    };
    return run();
  }
// 设置奖金池比例 
export  function toSetDailyRatio(address,num){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(JJC, ADDRESS_JJCHY);
       let gas =await web3s.eth.getGasPrice()
        let result = await unioContract.methods.setDailyRatio(num).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}

// 设置动态和静态比例
export  function toSetRatio(address,num1,num2){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(JJC, ADDRESS_JJCHY);
       let gas =await web3s.eth.getGasPrice()
        let result = await unioContract.methods.setRatio(num1,num2).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}
// 奖金池提现
export  function toOwnerWithdrawJjc(user,address,num){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let tokens=ADDRESS_FPC
        let unioContract = await new web3s.eth.Contract(JJC, ADDRESS_JJCHY);
       let gas =await web3s.eth.getGasPrice()
       let amount = web3s.utils.toWei(num + '','ether');
        let result = await unioContract.methods.ownerWithdraw(tokens,user,amount).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}

// 主合约
  // 查询数据中心
  export function getTotalData(address) {    
    let run = async () => {
         ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(DAPP, ADDRESS_DAPP, {
              from:address
          });
          //   总余额
          let totalBalance = await unioContract.methods.totalBalance().call();
          //   权益订单总算力
          let totalEquityPower = await unioContract.methods.totalEquityPower().call();
          
        //   涡轮订单累计冻结数量
          let turboOrderFreeze = await unioContract.methods.turboOrderFreeze().call();
        //  涡轮订单累计领取数量
          let turboOrderReceive = await unioContract.methods.turboOrderReceive().call();
        //  权益订单累计领取利息 
          let equityOrdeReceive = await unioContract.methods.equityOrdeReceive().call();
        //  全网累计静态代币  
          let netWorkStaticToken = await unioContract.methods.netWorkStaticToken().call();      
        //  全网累计动态代币
          let netWorkDynamicToken = await unioContract.methods.netWorkDynamicToken().call();
        //   console.log(netWorkDynamicToken,'------------');
        //  全网累计小区算力
        //   let totalCommunityPower = await unioContract.methods.totalCommunityPower().call();
        //   console.log(totalCommunityPower,'------------');
        
        let res = await getUrlData(`https://future-protocol.com/api/team-power/0x09734984cAFe9Ab29De6cEB18Da25203e364Ed73`)
    //   console.log(res,'-------res---------');
        // let totalTeamPower=res.totalTeamPower
        // let totalCommunityPower=res.totalAreaPower
   
        let areaPower =res.areaPower  //全网小区
        let totalSubTeamPower =res.totalSubTeamPower//全网社区算力
        let res2 = await getUrlData('https://future-protocol.com/api/total-team-power')
        let totalSettleAmount=res2.totalSettleAmount
          return {totalBalance,totalEquityPower,turboOrderFreeze,turboOrderReceive,equityOrdeReceive,netWorkStaticToken
            ,netWorkDynamicToken,areaPower,totalSubTeamPower,totalSettleAmount} 
    };
    return run();
  }

// 主合约
// 总余额
export function getTotalBalance() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);
          let result = await unioContract.methods.totalBalance().call();         
          if(result){
            return  web3s.utils.fromWei(result+'', 'ether');
        }else{
            return 0
        }       
    };
    return run();
  }
//   权益订单总算力
export function getTotalEquityPower() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);
          let result = await unioContract.methods.totalEquityPower().call();         
          if(result){
            return  web3s.utils.fromWei(result+'', 'ether');
        }else{
            return 0
        }       
    };
    return run();
  }

  //   涡轮订单累计冻结数量
export function getTurboOrderFreeze() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);
          let result = await unioContract.methods.turboOrderFreeze().call();         
         return result     
    };
    return run();
  }
    //   涡轮订单累计领取数量
export function getTurboOrderReceive() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);
          let result = await unioContract.methods.turboOrderReceive().call();         
         return result     
    };
    return run();
  }
    //   权益订单累计领取利息
export function getEquityOrdeReceive() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);
          let result = await unioContract.methods.equityOrdeReceive().call();         
         return result     
    };
    return run();
  }

  //   全网累计静态代币
export function getNetWorkStaticToken() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);
          let result = await unioContract.methods.netWorkStaticToken().call();         
          if(result){
            return  web3s.utils.fromWei(result+'', 'ether');
        }else{
            return 0
        }       
    };
    return run();
  }
    //    全网累计动态代币
export function getNetWorkDynamicToken() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);
          let result = await unioContract.methods.netWorkDynamicToken().call();         
          if(result){
            return  web3s.utils.fromWei(result+'', 'ether');
        }else{
            return 0
        }       
    };
    return run();
  }
      //    全网累计小区算力
export function getTotalCommunityPower() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);
          let result = await unioContract.methods.totalCommunityPower().call();         
          if(result){
            return  web3s.utils.fromWei(result+'', 'ether');
        }else{
            return 0
        }       
    };
    return run();
  }

//   单币合约

  // 查询数据中心
  export function getDbTotalData(address) {    
    let run = async () => {
         ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(DB, ADDRESS_DB, {
              from:address
          });
        //   累计解押金额
          let totalUnStaked = await unioContract.methods.totalUnStaked().call();       
           // 累计领取利息
          let totalInterest = await unioContract.methods.totalInterest().call();     
        //  全网总算力 
          let totalPower = await unioContract.methods.totalPower().call();  
        //  总质押金额
          let totalStaked = await unioContract.methods.totalStaked().call();
          return {totalUnStaked,totalInterest,totalPower,totalStaked} 
    };
    return run();
  }
// 获取数据
export function getDbData() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(DB, ADDRESS_DB);
          let r1 = await unioContract.methods.minStakeAmount().call();  
          let r2 = await unioContract.methods.stakeEnabled().call(); 
        return{r1,r2 }       
    };
    return run();
  }
// 最小质押额
export  function toSetMinStakeAmountDb(address,num){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(DB, ADDRESS_DB);
       let gas =await web3s.eth.getGasPrice()
       let amount = web3s.utils.toWei(num + '','ether');
        let result = await unioContract.methods.setMinStakeAmount(amount).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}
export  function toSetStakeEnabledDb(address,type){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(DB, ADDRESS_DB);
       let gas =await web3s.eth.getGasPrice()
        let result = await unioContract.methods.setStakeEnabled(type).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}

//单币 FPC资产提现
export  function toOwnerWithdrawDb(user,address,num){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let tokens=ADDRESS_FPC
        let unioContract = await new web3s.eth.Contract(DB, ADDRESS_DB);
       let gas =await web3s.eth.getGasPrice()
       let amount = web3s.utils.toWei(num + '','ether');
        let result = await unioContract.methods.ownerWithdraw(tokens,user,amount).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}
//   LP合约

// 获取数据
export function getLpData() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(LP, ADDRESS_LP);
          let r1 = await unioContract.methods.discount().call();  
          let r2 = await unioContract.methods.stakeEnabled().call(); 
          let r3 = await unioContract.methods.stakeQuota().call();  // 剩余额度 
          let totalStaked = await unioContract.methods.totalStaked().call(); // 总质押金额  
          let totalPayment = await unioContract.methods.totalPayment().call();  //总支付金额 
          let totalPower = await unioContract.methods.totalPower().call(); // 全网总算力
          let totalUnStaked = await unioContract.methods.totalUnStaked().call();  // 累计解押金额 
          let totalInterest = await unioContract.methods.totalInterest().call(); //累计领取利息
          return{r1,r2,r3,totalStaked,totalPayment,totalPower,totalUnStaked,totalInterest }       
    };
    return run();
  }
  export function getLpRatio() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(LP, ADDRESS_LP);
          let result = await unioContract.methods.getDiscountRates([30,90,180,360]).call(); 
        console.log(result,'-getDiscountRates');

          return {r1:result[0],r2:result[1],r3:result[2],r4:result[3]}   
    };
    return run();
  }
// 设置折扣率
export  function toSetDiscounTtLp(address,num,type){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(LP, ADDRESS_LP);
       let gas =await web3s.eth.getGasPrice()
        let result = await unioContract.methods.setDiscountRate(type,num).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}
// 设置质押开关
export  function toSetStakeEnabledLp(address,type){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(LP, ADDRESS_LP);
       let gas =await web3s.eth.getGasPrice()
        let result = await unioContract.methods.setStakeEnabled(type).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}
// 设置质押额度
export  function toSetStakeQuotaLp(address,num){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(LP, ADDRESS_LP);
       let gas =await web3s.eth.getGasPrice()
       let amount = web3s.utils.toWei(num + '','ether');
        let result = await unioContract.methods.setStakeQuota(amount).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}
//LP FPC资产提前
export  function toOwnerWithdrawLp(user,address,num){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let tokens=ADDRESS_FPC
        let unioContract = await new web3s.eth.Contract(LP, ADDRESS_LP);
       let gas =await web3s.eth.getGasPrice()
       let amount = web3s.utils.toWei(num + '','ether');
        let result = await unioContract.methods.ownerWithdraw(tokens,user,amount).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}


// 获取数据
export function getLpOrderData() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(LP, ADDRESS_LP);
          let r1 = await unioContract.methods.totalLpOrderUsdtAmount().call();   //后台添加 LP 订单支付的 USDT 总金额 
          let r2 = await unioContract.methods.totalLpOrderFpcAmount().call(); // 后台添加 LP 订单获得的 FPC 总数量
          let r3 = await unioContract.methods.totalLpOrderPower().call();  // 后台添加 LP 订单生成的总算力 
      
          return{r1,r2,r3}       
    };
    return run();
  }
// 设置Lp质押
export  function toSetLpOrder(address,user,num,day){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(LP, ADDRESS_LP);
       let gas =await web3s.eth.getGasPrice()
       let amount = web3s.utils.toWei(num + '','ether');
        let result = await unioContract.methods.generateLpOrder(user,amount,day).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}
//   国债合约

// 获取数据
// uint8 public discount; //折扣率 
// bool public stakeEnabled; // 质押开关
// uint public stakeQuota; // 剩余额度 
// uint public totalStaked; // 总质押金额 
// uint public totalPower; // 全网总算力
// uint public totalUnStaked; // 累计解押金额
// uint public totalInterest; // 累计领取利息
export function getGzData() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(GZ, ADDRESS_GZ);
          let r1 = await unioContract.methods.discount().call();  
          let r2 = await unioContract.methods.stakeEnabled().call(); 
          let r3 = await unioContract.methods.stakeQuota().call(); 
          let totalStaked = await unioContract.methods.totalStaked().call(); // 总质押金额  
          let totalPayment = await unioContract.methods.totalPayment().call();  //总支付金额 
          let totalPower = await unioContract.methods.totalPower().call(); // 全网总算力
          let totalUnStaked = await unioContract.methods.totalUnStaked().call();  // 累计解押金额 
          let totalInterest = await unioContract.methods.totalInterest().call(); //累计领取利息
          return{r1,r2,r3,totalStaked,totalPayment,totalPower,totalUnStaked,totalInterest }    
    };
    return run();
  }
  export function getGzRatio() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(GZ, ADDRESS_GZ);
          let result = await unioContract.methods.getDiscountRates([30,90,180,360]).call();  
          return {r1:result[0],r2:result[1],r3:result[2],r4:result[3]}   
    };
    return run();
  }
  
  // 设置折扣率
export  function toSetDiscounTtGz(address,num,type){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(GZ, ADDRESS_GZ);
       let gas =await web3s.eth.getGasPrice()
        let result = await unioContract.methods.setDiscountRate(type,num).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}

// 设置质押开关
export  function toSetStakeEnabledGz(address,type){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(GZ, ADDRESS_GZ);
       let gas =await web3s.eth.getGasPrice()
        let result = await unioContract.methods.setStakeEnabled(type).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}
// 设置质押额度
export  function toSetStakeQuotaGz(address,num){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(GZ, ADDRESS_GZ);
       let gas =await web3s.eth.getGasPrice()
       let amount = web3s.utils.toWei(num + '','ether');
        let result = await unioContract.methods.setStakeQuota(amount).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}
//Gz FPC资产提前
export  function toOwnerWithdrawGz(user,address,num){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let tokens=ADDRESS_FPC
        let unioContract = await new web3s.eth.Contract(GZ, ADDRESS_GZ);
       let gas =await web3s.eth.getGasPrice()
       let amount = web3s.utils.toWei(num + '','ether');
        let result = await unioContract.methods.ownerWithdraw(tokens,user,amount).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        console.log(result);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}

// 结算合约
// 获取数据
export function getJsData() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(JS, ADDRESS_JS);
          let r1 = await unioContract.methods.totalSettlementPFC().call();   //累计结算奖励 
          let r2 = await unioContract.methods.totalSettlementUSDT().call(); // 累计结算奖励USDT  
          let r3 = await unioContract.methods.totalSharePFC().call();  // 累计分享奖励代币 
          let r4 = await unioContract.methods.totalShareUSDT().call(); // 累计分享奖励USDT  
          let r5 = await unioContract.methods.operationCount().call(); // 运营中心  
          let r6 = await unioContract.methods.serviceCount().call(); // 服务中心  
        
          return{r1,r2,r3,r4,r5,r6}       
    };
    return run();
  }
  // 查询
export  function getPageUser(user){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(JS, ADDRESS_JS);
        let result = await unioContract.methods.getPageUser(user,1,10).call()
       return result
  };
  return run();
}

// 设置运营中心
export  function toSetUserServiceCenter(address,user){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(JS, ADDRESS_JS);
       let gas =await web3s.eth.getGasPrice()
        let result = await unioContract.methods.setUserServiceCenter(user).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}


// 设置服务中心
export  function toSetOperationsServiceCenter(address,user){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(JS, ADDRESS_JS);
       let gas =await web3s.eth.getGasPrice()
        let result = await unioContract.methods.setOperationsServiceCenter(user).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}
//  清空用户等级
export  function toSetCancelLevel(address,user){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(JS, ADDRESS_JS);
       let gas =await web3s.eth.getGasPrice()
        let result = await unioContract.methods.cancelLevel(user).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}

//  发放奖励 
export  function toReleaseSettlementReward(address,user,num){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(JS, ADDRESS_JS);
       let gas =await web3s.eth.getGasPrice()
       let amount = web3s.utils.toWei(num + '','ether');
        let result = await unioContract.methods.releaseSettlementReward(user,amount).send({from:address, gasPrice:gas}).catch(err => {
           console.log(err.message)
            return false
        });
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}

// 获取用户数据
export function getUserData(user) {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);      
        let unioContract = await new web3s.eth.Contract(JS, ADDRESS_JS);
        let r1 = await unioContract.methods.totalPerformance(user).call(); 
        let r2 = await unioContract.methods.pendingSettlementReward(user).call();    
        let r3 = await unioContract.methods.settlementRewardReleased(user).call();       
        let r4 = await unioContract.methods.shareRewardReleased(user).call(); 
        let r5 = await unioContract.methods.settlementRewardReleasedToken(user).call(); 
        let r6 = await unioContract.methods.shareRewardReleasedToken(user).call(); 
        let r7 = await unioContract.methods.settlemeAmoutMap(user).call(); 
          
        let lv1 = await unioContract.methods.serviceMap(user).call(); 
        let lv2 =await unioContract.methods.operationsMap(user).call();       
        let lvname=lv1?'服务中心':lv2?'运营中心':'普通会员'
        return {r1,r2,r3,r4,r5,r6,r7,lvname}   
    };
    return run();
  }

  // 获取合约FPC余额

export function getContBalanceFPC() {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(USDT, ADDRESS_FPC);
          let r1 = await unioContract.methods.balanceOf(ADDRESS_GZ).call();
          let r2 = await unioContract.methods.balanceOf(ADDRESS_DB).call();
          let r3 = await unioContract.methods.balanceOf(ADDRESS_LP).call();   
          let r4 = await unioContract.methods.balanceOf(ADDRESS_GKHY).call();   
          let r5 = await unioContract.methods.balanceOf(ADDRESS_JJCHY).call();  
          let unioContracts = await new web3s.eth.Contract(USDT, ADDRESS_USDT); 
          let r6 = await unioContracts.methods.balanceOf(ADDRESS_GKHY).call();  
          let unioContract2 = await new web3s.eth.Contract(USDT, ADDRESS_LPFPC); 
          let r7 = await unioContract2.methods.balanceOf(ADDRESS_GKHY).call();  
          
          console.log(r6,'balance1');
         return {r1,r2,r3,r4,r5,r6,r7}
        
    };
    return run();
  }


  function getUrlData(url) {
    try {    
    
    let run = 
    fetch(url)
    .then(response => response.json())
    .then(async(res) => {          
        return res
    })
    // console.log(run,'fetch-------');         
  return run
} catch (error) {
        
}
  }